package com.sunzm.common.utils.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

public class KafkaConsumerDemo {
    public static void main(String[] args) {

        String bootstrapServers = "82.156.210.70:9093";
        //服务器上运行，使用内网
        //String bootstrapServers = "10.0.8.11:9092";
        String topic = "my-topic";

        Properties properties = new Properties();

        // 设置kafka服务器地址
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        //设置key和value的反序列化方式
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        //设置消费者组ID
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "my-group");
        //设置一个唯一的客户端ID（可选，如果不设置，会自动生成）
        properties.put(ConsumerConfig.CLIENT_ID_CONFIG, "my-client-id");

        //设置从最新(latest)还是最早(earliest)消费
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");

        // 定义 consumer
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

        // 消费者订阅的 topic, 可同时订阅多个
        consumer.subscribe(Arrays.asList(topic));

        while (true) {
            // 读取数据，读取超时时间为 100ms
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
            for (ConsumerRecord<String, String> record : records)
                System.out.printf("偏移量 = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
        }

    }
}
